package com.zoke.dappstore.tools;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;

import com.zoke.dappstore.Conf;
import com.zoke.neb.tool.PersistTool;

import java.io.File;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by wulijie on 2018/6/11.
 */
public class Tools {
    public static String formatSize(String size) {
        if (TextUtils.isEmpty(size))
            return "0 MB";
        DecimalFormat ff = new DecimalFormat("##0.00");
        float s = Float.parseFloat(size) / (1024f * 1024f);
        return ff.format(s) + " MB";
    }

    public static String getAddress() {
        String address = PersistTool.getString(Conf.KEY, "");
        if (TextUtils.isEmpty(address)) address = Conf.DEFAULT_ADDRESS;
        return address;

    }


    public static String getFilePath(String name) {
        String path = Environment.getExternalStorageDirectory().toString();
        path = path + "/dapp/apk/" + name;
        return path;
    }


    public static String formatTime(String time) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formatter.format(new Date(Long.parseLong(time)));
    }

    /**
     * 通过隐式意图调用系统安装程序安装APK
     */
    public static void install(Context context, String filePath) {
        File file = new File(filePath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri =
                    FileProvider.getUriForFile(context, "com.zoke.dappstore.fileprovider", file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file),
                    "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }


    /**
     * 获取当前本地apk的版本
     *
     * @param mContext
     * @return
     */
    public static int getVersionCode(Context mContext) {
        int versionCode = 0;
        try {
            //获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = mContext.getPackageManager().
                    getPackageInfo(mContext.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

}
